package com.chen.cloud.micro.provider.user.controller;

import com.chen.cloud.micro.provider.user.entity.User;
import com.chen.cloud.micro.provider.user.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collection;

/**
 * @author ChenTian
 * @date 2022/6/1
 */
@RestController
@RequestMapping("/user/v1")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserRepository userRepository;

    @GetMapping("/{id}")
    public User findById(@PathVariable Long id){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(principal instanceof UserDetails){
            UserDetails user = (UserDetails) principal;
            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            for(GrantedAuthority authority : authorities){
                logger.info("当前用户是:{}, 角色是:{}", user.getUsername(), authority.getAuthority());
            }
        }
        User entity = userRepository.findOne(id);
        return entity;
    }

}
